<template>
	<div>
		<el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" v-model="visible" width="50%" @close="refreshEmit" >
			<el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter.native="dataFormSubmit(dataFormRef)" label-width="120px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="用户名" prop="username">
							<el-input v-model="dataForm.username" placeholder="登录帐号" v-bind:disabled="disabledInput" :maxlength="50"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="姓名" prop="staffName" :class="{ 'is-required': !dataForm.id }">
							<el-input v-model="dataForm.staffName" placeholder="姓名" :maxlength="50"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
				<el-col :span="12">
					<el-form-item label="员工编号" prop="staffId">
						<el-input ref="staffIdInput" placeholder="员工编号" v-model="dataForm.staffId"  :maxlength="50">
					</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="部门" prop="orgId">
						<el-tree-select v-model="dataForm.orgId" :data="treeList" check-strictly filterable  style="width:100%"></el-tree-select>
						<!-- <SelectTree v-model="dataForm.orgId" :options="treeList" :lazy="false" selectStyle="width:100%"></SelectTree> -->
						<!-- <el-select v-model="dataForm.orgId" placeholder="" :filterable="true" style="width: 100%;" >
							<el-option v-for="(item,index) in treeList" :key="item.key" :label="item.value" :value="item.key"></el-option>
						</el-select> -->
					</el-form-item>
				</el-col>
				</el-row>
				<el-row>
				<el-col :span="12">
					<el-form-item label="邮箱" prop="email">
						<el-input v-model="dataForm.email" placeholder="邮箱" :maxlength="100"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="手机号" prop="mobile" :maxlength="100">
						<el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
					</el-form-item>
				</el-col>
				</el-row>
				<el-row>
				<el-col :span="12">
					<el-form-item label="证件类型" prop="idType">
					<DicSelect v-model="dataForm.idType" placeholder="请选择" dicCode="1032" style="width:100%"></DicSelect>
					<!-- <rf-combo-box v-model="dataForm.idType" placeholder="请选择" dicCode="1032"></rf-combo-box> -->
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="证件号码" prop="idNo">
						<el-input v-model="dataForm.idNo" placeholder="证件号码" :maxlength="50" ></el-input>
					</el-form-item>
				</el-col>
				</el-row>
				<el-row>
				<el-col :span="12">
					<el-form-item label="状态" prop="status">
						<DicSelect v-model="dataForm.status" placeholder="请选择" dicCode="1002" :excludeIsKey="userStatusExl" style="width:100%"></DicSelect>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item v-if="istenant && userInfos.tenantId === '1'" label="租户" prop="tenantId" >
						<!-- <DicSelect v-model="dataForm.tenantId" placeholder="请选择" :isTenantSelect="true" :filterable="true" style="width:100%" :isDisabled="!(!dataForm.id) || userInfos.value.tenantId !== '1'" @change="changeState"></DicSelect> -->
						<el-select v-model="dataForm.tenantId" placeholder="" :filterable="true" :disabled="!(!dataForm.id)" style="width: 100%;" @change="changeState">
							<el-option v-for="(item,index) in tenantSelect" :key="item.key" :label="item.value" :value="item.key"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="visible = false">取消</el-button>
					<el-button type="primary" @click="dataFormSubmit(dataFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted,  defineComponent } from 'vue';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import {systemApi} from '/@/api/systemapi'
import type { FormInstance } from 'element-plus'
import { getCodeList } from '/@/utils/cacheDict'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
export default defineComponent ({
	// components: { DicSelect },
	setup(props, ctx) {
		const stores = useUserInfo()
		const { userInfos } = storeToRefs(stores)
		const dataFormRef = ref<FormInstance>()
		const state = reactive({
			visible: false,
			istenant: import.meta.env.VITE_IS_TENANT,
			disabledInput: true,
			treeList: [],
			tenantSelect: [],
			dataDictionaryList: {},
			userStatusExl: ["100204"],
			dataForm: {
				id: '',
				username: "",
				salt: "",
				email: "",
				mobile: "",
				status: "100201",
				orgName: "",
				orgId: "",
				staffId: "",
				staffName: "",
				idType: "01",
				idNo: "",
				tenantId: userInfos.value.tenantId
			},
			dataRule: {
				username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
				staffName:[{ required: true, message: "姓名不能为空", trigger: "blur" }],
				orgId: [{ required: true, message: "部门不能为空", trigger: "blur" }],
				status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
				tenantId: [{ required: true, message: '请选择租户', trigger: 'blur' }]
			}
		})
		// 页面加载时
		onMounted(() => {
			// 加载租户
			getTenantSelect();
			// 数据字典
			getCodeList(state, ['1002', '1032'])
		})
		// 打开弹窗
		const openDialog = (id: string, tenantId: string) => {
			state.dataForm = {
				id: '',
				username: "",
				salt: "",
				email: "",
				mobile: "",
				status: "100201",
				orgName: "",
				orgId: "",
				staffId: "",
				staffName: "",
				idType: "01",
				idNo: "",
				tenantId: userInfos.value.tenantId
			}
			if(!id){
				state.dataForm.id = id
				state.disabledInput = false
			}else{
				state.dataForm.id = id
				//加载原数据
				systemApi().getUserInfoById(id).then(data => {
					if (data && data.code === 0) {
						state.dataForm.username = data.user.username
						state.dataForm.salt = data.user.salt
						state.dataForm.email = data.user.email
						state.dataForm.mobile = data.user.mobile
						state.dataForm.status = data.user.status
						state.dataForm.orgName = data.user.orgName
						state.dataForm.orgId = data.user.orgId
						state.dataForm.staffId = data.user.staffId
						state.dataForm.staffName = data.user.staffName
						state.dataForm.idType = data.user.idType
						state.dataForm.idNo = data.user.idNo
						state.dataForm.tenantId = data.user.tenantId
					}
				})
			}
			state.visible = true
			getTreeList(tenantId)
		}
		const refreshEmit = () => {
			closeDialog()
			ctx.emit('refreshDataList')
		}
		// 关闭弹窗
		const closeDialog = () => {
			state.visible = false;
		}
		const dataFormSubmit = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.validate((valid: boolean) => {
				if (valid) {
					const loading = ElLoading.service({
						lock: true,
						text: '处理中',
						background: 'rgba(0, 0, 0, 0.7)',
					})
					if (!state.dataForm.id) {
						//新增
						systemApi().saveUserInfo(state.dataForm, []).then(data => {
							if (data && data.code === 0) {
								ElMessage.success('保存成功')
								ctx.emit('refreshDataList')
								state.visible = false
							}else{
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						}).finally(() => {
							loading.close()
						})
					}else{
						//修改
						systemApi().updateUserInfo(state.dataForm, []).then(data => {
							if (data && data.code === 0) {
								ElMessage.success('保存成功')
								ctx.emit('refreshDataList')
								state.visible = false
							}else{
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						}).finally(() => {
							loading.close()
						})
					}
				}
			})
		}
		const getTreeList = (value: string) => {
			systemApi().getOrgsByTenantIdEl(value).then(data => {
				if (data) {
					state.treeList = data;
				} else {
					state.treeList = [];
				}
			})
		}
		const changeState = (value: any) => {
			if (!value) {
				ElMessage.warning('请选择租户')
				return
			}
			state.dataForm.orgId = ''
			getTreeList(value)
		}
		const getTenantSelect = () => {
			systemApi().getTenantSelect().then(data => {
				if (data && data.code === 0) {
				state.tenantSelect = data.list
				}
			})
		}
		return{
			userInfos,
			dataFormRef,
			openDialog,
			closeDialog,
			refreshEmit,
			dataFormSubmit,
			getTreeList,
			changeState,
			getTenantSelect,
			...toRefs(state),
		}
	}
})
</script>